<template>
  <div class="noticebox beautifulScroll">
    <!-- 头部 -->
    <div class="casetop">
      <div class="caseback" v-if="!xqshow" @click="back"
        ><van-icon name="arrow-left"
      /></div>
      <div class="caseback" @click="xqshow = false" v-if="xqshow"
        ><van-icon name="arrow-left"
      /></div>
      <div class="casename"
        >消息<div class="casetotal">{{ imessagetotal }}</div></div
      >
      <div class="selcetboximg caseselect" @click="onSelect"
        ><img src="@/assets/images/clear.png" alt="" />一键已读
      </div>
    </div>
    <!-- 自定义刷新提示 -->

    <!-- 内容 -->
    <div
      class="outmain beautifulScroll"
      @scroll="handleScroll"
      ref="scrollContainer"
      v-if="!xqshow"
    >
      <!-- 下拉刷新提示 -->
      <div v-if="isRefreshing" class="refreshing">正在刷新...</div>
      <!-- 展示数据 -->
      <van-swipe-cell
        v-for="item in renderData"
        :key="item.msgNoticeId"
        class="outmains"
      >
        <div class="outbox" @click="goxq(item)">
          <div class="outicon">
            <img src="@/assets/images/ydic.png" alt="" />
            <div class="outicony" v-if="item.readStatus != '1'"></div>
            <div class="outname">{{ item.title }}</div>
            <div class="outtimer">{{ formatTime(item.createTime) }}</div>
            <!-- {{ item.readStatus == '1' ? '已读' : '未读' }} -->
          </div>
          <div class="outdesbox">
            {{ item.content }}
          </div>
        </div>
        <template #right>
          <van-button
            square
            type="primary"
            text="标记已读"
            class="delete-button"
            :disabled="item.readStatus == 0 ? false : true"
            @click="readfn(item.msgNoticeId)"
          />

          <van-button
            square
            text="标记删除"
            type="danger"
            class="delete-button"
            @click="Delfn(item.msgNoticeId)"
          />
        </template>
      </van-swipe-cell>
      <!-- 触底加载提示 -->
      <div v-if="isLoading" class="loading">加载更多...</div>
      <div v-if="finished" class="loading">没有数据了！</div>
    </div>
    <!-- 详情内容展示 -->
    <div class="xqbox beautifulScroll" v-if="xqshow">
      <textarea :placeholder="content" :disabled="true"></textarea>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import {
    noticeList,
    noticeRead,
    noticeDel,
    noticeReadall,
  } from '@/api/outBox';
  import { reactive, ref, onMounted, onBeforeUnmount } from 'vue';
  import { storeToRefs } from 'pinia';
  import { useUserStore } from '@/store';
  import { Pagination } from '@/types/global';
  import { showSuccessToast, showFailToast } from 'vant';
  const userStore = useUserStore();
  const userdata = storeToRefs(userStore);
  const studentId = ref(userdata.studentId.value);
  import { useRouter, useRoute } from 'vue-router';
  const router = useRouter();
  const route = useRoute();
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const formatTime = (isoString) => {
    const date = new Date(isoString); // 将 ISO 字符串转为 Date 对象
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，补零
    const day = String(date.getDate()).padStart(2, '0'); // 补零
    const hours = String(date.getHours()).padStart(2, '0'); // 补零
    const minutes = String(date.getMinutes()).padStart(2, '0'); // 补零
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  };
  // 定义消息total
  const imessagetotal = ref(0);

  const pagination = reactive({ ...basePagination });

  const renderData = ref([]); // 渲染的数据列表

  // 请求数据方法
  const fetchData = async (isRefresh = false) => {
    try {
      const res = await noticeList({
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
        studentId: studentId.value,
      });
      const newData = res.data.list || [];
      if (isRefresh) {
        renderData.value = newData; // 刷新时替换数据
      } else {
        renderData.value = [...renderData.value, ...newData]; // 加载更多时追加数据
      }
      finished.value = renderData.value.length >= res.data.total; // 检查是否加载完成
      imessagetotal.value = res.data.total;
    } finally {
      // console.log('加载完成了吗', loading.value);
    }
  };

  // 下拉刷新逻辑
  const onRefresh = async () => {
    console.log('触发了刷新');

    pagination.current = 1; // 重置页码
    await fetchData(true); // 刷新数据
    isRefreshing.value = false;
  };

  // 触底加载逻辑
  const onLoadMore = async () => {
    if (finished.value) return;
    pagination.current += 1;
    await fetchData(); // 加载更多数据
    isLoading.value = false;
  };
  // 已读
  const readfn = (msgNoticeId) => {
    console.log('标记', msgNoticeId);

    noticeRead({ msgNoticeId: msgNoticeId }).then((res: any) => {
      if (res.code == 200) {
        showSuccessToast('成功');

        onRefresh();
      } else {
        showFailToast('失败');
      }
    });
  };
  // 删除
  const Delfn = (msgNoticeId) => {
    noticeDel({ msgNoticeId: msgNoticeId }).then((res: any) => {
      if (res.code == 200) {
        showSuccessToast('成功');

        onRefresh();
      } else {
        showFailToast('失败');
      }
    });
  };
  //
  const actions = [{ name: '清空' }];
  const show = ref(false);
  // 清空一键
  const onClickRight = () => {
    show.value = true;
  };
  const onSelect = (item) => {
    noticeReadall({
      studentId: studentId.value,
    }).then((res: any) => {
      if (res.code == 200) {
        showSuccessToast('成功');

        onRefresh();
      } else {
        showFailToast('失败');
      }
    });
  };
  // 初始加载
  onMounted(() => {
    fetchData();
    bindTouchEvents();
  });

  //  滚动判断
  const scrollContainer = ref<HTMLElement | null>(null);
  const isRefreshing = ref(false);
  const isLoading = ref(false);
  const finished = ref(false);
  let startY = 0; // 记录触摸开始的位置
  let startX = 0; // 记录触摸开始的横向位置
  let isVerticalScroll = false; // 是否为垂直滚动

  // 下拉刷新处理
  const handleTouchStart = (event: TouchEvent) => {
    startY = event.touches[0].clientY;
    startX = event.touches[0].clientX;
    isVerticalScroll = false; // 重置滚动方向
  };

  let debounceTimeout: ReturnType<typeof setTimeout>;

  const handleTouchMove = (event: TouchEvent) => {
    const moveY = event.touches[0].clientY;
    const moveX = event.touches[0].clientX;
    const diffY = Math.abs(moveY - startY);
    const diffX = Math.abs(moveX - startX);

    // 判断是否为垂直滚动（如果垂直位移大于水平位移）
    if (!isVerticalScroll && diffY > diffX) {
      isVerticalScroll = true;
    }

    if (!isVerticalScroll) {
      // 如果不是垂直滚动，直接返回
      return;
    }

    if (scrollContainer.value && scrollContainer.value.scrollTop > 0) {
      return; // 如果不是在顶部，则不处理下拉刷新
    }

    clearTimeout(debounceTimeout); // 清除上一次的定时器
    debounceTimeout = setTimeout(() => {
      if (moveY - startY > 50 && !isRefreshing.value) {
        // 判断下拉超过50px
        isRefreshing.value = true;
        onRefresh();
      }
    }, 300); // 防抖：300ms
  };

  const handleTouchEnd = () => {
    startY = 0; // 清除触摸开始位置
    startX = 0; // 清除横向触摸开始位置
    isVerticalScroll = false; // 重置方向标志
    if (isRefreshing.value) {
      console.log('刷新已完成');
    }
  };

  // 触底加载处理
  let lastScrollTime = 0;

  const handleScroll = (event: Event) => {
    if (isRefreshing.value) return; // 正在刷新时，不触发触底加载
    const now = Date.now();
    if (now - lastScrollTime > 300) {
      lastScrollTime = now;
      const container = event.target as HTMLElement;
      if (
        container.scrollTop + container.clientHeight >=
          container.scrollHeight - 100 &&
        !isLoading.value
      ) {
        if (finished.value) return;
        isLoading.value = true;
        console.log('触底了');
        onLoadMore();
      }
    }
  };

  // 绑定触摸事件
  const bindTouchEvents = () => {
    if (scrollContainer.value) {
      scrollContainer.value.addEventListener('touchstart', handleTouchStart);
      scrollContainer.value.addEventListener('touchmove', handleTouchMove);
      scrollContainer.value.addEventListener('touchend', handleTouchEnd);
    }
  };

  // 清除触摸事件
  const unbindTouchEvents = () => {
    if (scrollContainer.value) {
      scrollContainer.value.removeEventListener('touchstart', handleTouchStart);
      scrollContainer.value.removeEventListener('touchmove', handleTouchMove);
      scrollContainer.value.removeEventListener('touchend', handleTouchEnd);
    }
  };

  // 生命周期钩子：组件卸载时清除事件
  onBeforeUnmount(() => {
    unbindTouchEvents();
  });
  // 滚动判断逻辑完成
  const xqshow = ref(false);
  const content = ref();
  const goxq = (item: any) => {
    // console.log('点击了详情', item);
    content.value = item.content;
    xqshow.value = true;

    noticeRead({ msgNoticeId: item.msgNoticeId }).then((res: any) => {
      if (res.code == 200) {
        onRefresh();
      } else {
      }
    });
  };
  const back = () => {
    if (window.history.length > 1) {
      // 如果有历史记录，返回上一页
      router.back();
    } else {
      // 如果没有历史记录，跳转到默认页面
      router.push('/');
    }
  };
</script>

<style scoped>
  .xqbox {
    background-color: #fff;
    margin: 0 auto;
    width: 690px;
    height: 80%;
    border-radius: 20px;
    padding: 20px;
    color: #666666;
    font-size: 26px;
    overflow-y: auto;
  }
  .outtimer {
    color: #5a6067;
    font-size: 24px;
  }
  .outname {
    font-size: 30px;
    font-weight: 500;

    width: 420px;
    white-space: nowrap; /* 禁止换行 */
    overflow: hidden; /* 超出隐藏 */
    text-overflow: ellipsis; /* 显示省略号 */
  }
  .outbox {
    display: flex;

    font-size: 24px;
    height: 130px;
    border-radius: 20px;
    background-color: #fff;
    flex-direction: column;
    position: relative;
    padding: 15px;
  }
  .loading {
    font-size: 30px;
    text-align: center;
    color: #666666;
  }

  .outicony {
    position: absolute;
    height: 10px;
    width: 10px;
    background-color: red;
    border-radius: 50%;
    top: 20px;
    left: 15px;
  }
  .outdesbox {
    padding: 5px 10px;
    font-size: 24px;
    color: #666666;
    width: 665px;
    white-space: nowrap; /* 禁止换行 */
    overflow: hidden; /* 超出隐藏 */
    text-overflow: ellipsis; /* 显示省略号 */
  }
  .outicon {
    display: flex;
    align-items: center;
  }
  .delete-button {
    height: 100%;
  }
  .outicon img {
    width: 62px;
    height: 62px;
  }

  .noticebox {
    width: 100%;
    height: 100%;
    background: linear-gradient(180deg, #5f6d7c 0%, #f4f4f4 25%);
    position: absolute;
    top: 0;
    left: 0px;
  }
  .outmain {
    width: 100%;
    padding: 0px 20px;

    height: 100%;
    overflow-y: auto;
    padding-bottom: 100px;
  }
  .outmains {
    margin: 10px 0;
  }
  .casetop {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 30px 0;
    font-size: 32px;
    color: #ffff;
    position: relative;
    top: 0px;
    left: 0;
  }
  .caseback {
    font-size: 36px;
    color: #ffff;
    position: absolute;
    left: 20px;
  }
  .casename {
    display: flex;
    align-items: center;
  }
  .casetotal {
    width: 29px;
    height: 29px;
    background: #ffffff;
    border-radius: 50%;
    align-items: center;
    display: flex;
    justify-content: center;
    color: #53606f;
    font-size: 18px;
    margin: 0px 10px;
  }
  .caseselect {
    position: absolute;
    right: 25px;
    width: 130px;
    height: 37px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 41px 41px 41px 41px;
    font-size: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .caseselect img {
    width: 25px;
    height: 25px;
    display: block;
  }
</style>
